//
//  MallViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/10.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "MallViewController.h"
#import "MyGradesViewController.h"
#import "OrderViewController.h"
#import "GoodsDetailViewController.h"
#import "GoodsModel.h"
#import "MallRequestManager.h"
#import "UIImageView+WebCache.h"
#import "HeaderView.h"
#import "FooterView.h"
#import "FooterView.h"
#import "MallDataCell.h"
#import "LoginViewController.h"
//cell的重用标志MallDataCell
#define kCellReuseId  (@"cellId")
//header的重用标志
#define kHeaderReuseId  (@"HeaderId")
//footer的重用标志
#define kFooterReuseId  (@"FooterId")
#define kWidth (self.view.frame.size.width)
#define kHeight (self.view.frame.size.height)
#define kRGBColor(R,G,B)        [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0]
@interface MallViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    //网格视图
    UICollectionView *_collectionView;
}
@property (nonatomic, strong) NSMutableArray *dataSource0;
@property (nonatomic, strong) NSMutableArray *dataSource1;
@property (nonatomic, strong) NSMutableArray *dataSource2;
@property (nonatomic, strong) NSMutableArray *titleArray;

@property (strong, nonatomic) UIImageView *imageEmptyCategory;
@property (strong, nonatomic) UILabel *labelEmptyCategory;
//提示内容
- (void)showLabelEmptyCate:(CGRect)frame withTitle:(NSString *)title withImage:(UIImage *)image;
//清空提示信息
- (void)clearLabelEmptyCate;
@end

@implementation MallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"商城";
    [self showNavgationWithLeftItemWithTitle:@"首页"];
    self.view.backgroundColor = kRGBColor(235, 235, 235);
    
    //数据源
    [self createData];

}

- (void)createData
{
    NSString *userID;
    NSString *token;
    if (self.youke ==YES) {
        userID = @"0";
        token = Tmptoken;
    }else
    {
        userID = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
        token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    }
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setObject:userID forKey:@"user_id"];
    [params setObject:token forKey:@"token"];
    NSNumber *typeid = [NSNumber numberWithInt:0];
    [params setObject:typeid forKey:@"typeid"];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [MallRequestManager post:Querygoodslist RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:YES];
            return ;
        }else
        {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
            if ([dic.allKeys containsObject:@"result"]) {
                NSArray *result = [dic objectForKey:@"result"];
                NSLog(@"result:%@",result);
                self.dataSource0 = [NSMutableArray new];
                self.dataSource1 = [NSMutableArray new];
                self.dataSource2 = [NSMutableArray new];
                for (NSDictionary *dic in result) {
                    if ([dic.allKeys containsObject:@"good_type"]) {
                        if ([dic[@"good_type"]isEqualToString:@"3"]) {
                            [self.dataSource2 addObject:[GoodsModel appWithDict:dic]];
                        }
                        if ([dic[@"good_type"]isEqualToString:@"2"]) {
                            [self.dataSource1 addObject:[GoodsModel appWithDict:dic]];
                        }
                        if ([dic[@"good_type"]isEqualToString:@"1"]) {
                            [self.dataSource0 addObject:[GoodsModel appWithDict:dic]];
                        }
                    }
                }
                
                [self performSelectorOnMainThread:@selector(createCollectionView) withObject:nil waitUntilDone:NO];
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"后台数据有误" duration:0.0f];
            }
        }
    }];
}

- (void)showError
{
     [self showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"出错了，稍后再试吧" withImage:[UIImage imageNamed:@"icon_wifi"]];
}

//创建网格视图
- (void)createCollectionView
{
    
    //布局对象
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    //网格视图
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 51, kWidth, kHeight-20-50) collectionViewLayout:layout];
    //设置代理和数据源代理
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    //设置背景颜色
    _collectionView.backgroundColor = [UIColor whiteColor];
    //注册cell
    [_collectionView registerNib:[UINib nibWithNibName:@"MallDataCell" bundle:nil] forCellWithReuseIdentifier:kCellReuseId];
    //注册header
    
    [_collectionView registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kHeaderReuseId];
    //注册footer
    [_collectionView registerClass:[FooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kFooterReuseId];
    
    //添加到父视图
    [self.view addSubview:_collectionView];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionView代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
        switch (section) {
            case 0:
                return  self.dataSource0.count;
                break;
            case 1:
                return  self.dataSource1.count;
                break;
            case 2:
                return  self.dataSource2.count;
                break;
            default:
                break;
        }
       return 0;
}
//返回每个cell对象
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MallDataCell *cell = (MallDataCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCellReuseId forIndexPath:indexPath];
    CALayer *layer = [cell.imgView layer];
    layer.borderColor = [UIColor grayColor].CGColor;
    layer.borderWidth = 0.5f;
    switch (indexPath.section) {
        case 0:
        {
            GoodsModel *model  = self.dataSource0[indexPath.item];
            [cell config:model];
            return cell;
            
        }
            break;
        case 1:
        {
            GoodsModel *model  = self.dataSource1[indexPath.item];
            [cell config:model];
            return cell;
        }
            break;
        case 2:
        {
            GoodsModel *model  = self.dataSource2[indexPath.item];
            [cell config:model];
            return cell;
        }
            break;
        default:
            break;
    }
    return nil;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    GoodsDetailViewController *goodsDetail = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"GoodsDetail"];
    goodsDetail.youke = self.youke ;
    [self.navigationController pushViewController:goodsDetail animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            GoodsModel *model = self.dataSource0[indexPath.item];
            goodsDetail.goodsId = model.goodsId;
        }
            break;
        case 1:
        {
            GoodsModel *model = self.dataSource1[indexPath.item];
            goodsDetail.goodsId = model.goodsId;
        }
            break;
        case 2:
        {
            GoodsModel *model = self.dataSource2[indexPath.item];
            goodsDetail.goodsId = model.goodsId;
        }
            break;
        default:
            break;
    }
}
//上下左右的间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 20, 10, 20);
}
//cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (iPhone6P) {
        return CGSizeMake((kWidth-60)/2, 230);

    }
    return CGSizeMake((kWidth-60)/2, 210);
}
//横向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5;
}
//纵向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

//返回header对象
//返回footer对象
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        //header类型
        
        //从重用队列里面获取
        HeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kHeaderReuseId forIndexPath:indexPath];
        header.imgView.image = [UIImage imageNamed:@"goods_middle"];
        
        NSArray *array = @[@"久乐健康机器人",@"久乐健康机器人附属产品",@"小礼品"];
        self.titleArray = [NSMutableArray arrayWithArray:array];
        if (self.dataSource0.count==0) {
            [self.titleArray replaceObjectAtIndex:0 withObject:@""];
            header.imgView.hidden =YES;
        }
        if (self.dataSource1.count==0) {
            [self.titleArray replaceObjectAtIndex:1 withObject:@""];
             header.imgView.hidden =YES;
        }
        if (self.dataSource2.count==0) {
            [self.titleArray replaceObjectAtIndex:2 withObject:@""];
             header.imgView.hidden =YES;
        }
        //显示数据
        NSString *text = [self.titleArray objectAtIndex:indexPath.section];
        header.titleLabel.text = text;
        if (![text isEqualToString:@""]) {
            header.imgView.hidden =NO;
        }
        return header;
        
    }else if (kind == UICollectionElementKindSectionFooter){
        
        //从重用队列获取
        FooterView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kFooterReuseId forIndexPath:indexPath];
        //设置背景颜色
        footer.backgroundColor = [UIColor whiteColor];
       
        return footer;
    }
    
    return nil;
}

//header的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(kWidth, 40);
}

//footer的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(kWidth, 1);
}
- (IBAction)gradesButtonClicked:(UIButton *)sender {
    if ( self.youke ==YES) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登录,是否立即登录" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alter.delegate = self;
        [alter show];
        return;
    }
    MyGradesViewController *grades = [[MyGradesViewController alloc]init];
    [self.navigationController pushViewController:grades animated:YES];
}

- (IBAction)orderButtonClicked:(UIButton *)sender {
    if ( self.youke ==YES) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登录,是否立即登录" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alter.delegate = self;
        [alter show];
        return;
    }
    OrderViewController *userInfo = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OrderViewController"];
    [self.navigationController pushViewController:userInfo animated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex ==1) {
        LoginViewController *login = getStoryOfControllerInstance(@"LoginViewController");
        BaseNavController *baseNav = [[BaseNavController alloc] initWithRootViewController:login];
        [UIApplication sharedApplication].delegate.window.rootViewController = baseNav;
    }else
    {
        return;
    }
}
- (void)showLabelEmptyCate:(CGRect)frame withTitle:(NSString *)title withImage:(UIImage *)image{
    self.imageEmptyCategory = [[UIImageView alloc] initWithFrame:frame];
    self.imageEmptyCategory.image = image;
    [self.view addSubview:self.imageEmptyCategory];
    [self.view bringSubviewToFront:self.imageEmptyCategory];
    self.labelEmptyCategory = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.imageEmptyCategory.frame), [UIScreen mainScreen].bounds.size.width, 40)];
    self.labelEmptyCategory.textAlignment = NSTextAlignmentCenter;
    self.labelEmptyCategory.textColor = [UIColor grayColor];
    self.labelEmptyCategory.text = title;
    self.labelEmptyCategory.hidden = NO;
    self.labelEmptyCategory.font = [UIFont boldSystemFontOfSize:19];
    [self.view addSubview:self.labelEmptyCategory];
    [self.view bringSubviewToFront:self.labelEmptyCategory];
}

- (void)clearLabelEmptyCate{
    if (self.labelEmptyCategory.hidden == NO && self.labelEmptyCategory != nil) {
        self.labelEmptyCategory.hidden = YES;
        self.imageEmptyCategory.hidden = YES;
    }
}
@end
